package com.nami.web.controller;

import com.nami.common.response.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 登录控制器
 *
 * @author C
 */

@Controller
@Slf4j
@RequiredArgsConstructor
public class LoginController {

    private final AuthenticationManager authenticationManager;

    /**
     * 进入登录页面
     *
     * @return 去登录页面
     */
    @GetMapping({"/login", "/", ""})
    public String toLogin() {
        return "/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public R<Void> login(String username, String password) {
        log.info("username: {}, password: {}", username, password);
        log.info("验证用户信息");
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        log.info("验证用户信息结束");
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        return R.ok();
    }
}
